// 样式-数据-过滤图表
import React from 'react';
import { Checkbox, Row } from 'antd';
import FormItem from 'antd/lib/form/FormItem';
import { NO_FILTER_TYPES } from './EnumConfig';

interface IProps {
	config: any;
	onValuesChange: ( chartType: string, key: string, values: Object, configType: string ) => void;
	form: any;
	allConfigs: any;
}

const FilterCharts = ( props: IProps ) => {
	const { allConfigs, config, onValuesChange } = props;
	let chartsFilterList = [];
	const [ checkedList, setCheckedList ] = React.useState( config.data.filtersDataType || [] );

	if ( allConfigs ) {
		chartsFilterList = allConfigs
			.filter( ( item ) => {
				return NO_FILTER_TYPES.indexOf( item.type.toUpperCase() ) === -1 && item.data.tableName === config.data.tableName;
			} )
			.map( ( item ) => {
				return {
					key: item.key,
					type: item.type,
					title: item.style.titleValue,
				};
			} );
	}

	const [ indeterminate, setIndeterminate ] = React.useState( checkedList.length < chartsFilterList.length );
	const [ checkAll, setCheckAll ] = React.useState( !chartsFilterList.some( k => checkedList.indexOf( k.key ) === -1 ) );

	const onChange = list => {
		setCheckedList( list );
		setIndeterminate( !!list.length && list.length < chartsFilterList.length );
		setCheckAll( list.length === chartsFilterList.length );
		onValuesChange( config.type, config.key, { filtersDataType: list }, 'data' );
	};

	const onCheckAllChange = e => {
		const checkedList = e.target.checked ? chartsFilterList.map( v => v.key ) : [];
		setCheckedList( checkedList );
		setIndeterminate( false );
		setCheckAll( e.target.checked );
		onValuesChange( config.type, config.key, { filtersDataType: checkedList }, 'data' );
	};

	// name="filtersDataType"
	return (
		<>
			<FormItem label="关联的图表">
				<Row>
					<Checkbox indeterminate={ indeterminate } onChange={ onCheckAllChange } checked={ checkAll }>
						全选
					</Checkbox>
				</Row>


				<Checkbox.Group value={ checkedList } onChange={ onChange }>
					{ chartsFilterList.map( ( item: any ) => {
						return (
							<Row key={ item.key }>
								<Checkbox value={ item.key } key={ item.key }>
									{ item.title }
								</Checkbox>
							</Row>
						);
					} ) }
				</Checkbox.Group>
			</FormItem>
		</>
	);
};

export default React.memo( FilterCharts );
